package org.yx.controller;

import com.xiaoleilu.hutool.io.IoUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

import com.jfinal.core.JFinal;
import com.xiaoleilu.hutool.io.FileUtil;
import yxmes.tools.FineReportUtil;

@RequestMapping("/export")
public class DownloadController extends JbootController {
    public void index() {
        String fileName = getPara("fileName");

        String filePath = FineReportUtil.getFilePath() + fileName;//JFinal.me().getConstants().getBaseDownloadPath() + "/export/" + fileName;

        File destFile = FileUtil.file(filePath);
        if (!destFile.exists()) {
            renderText("Can not find file(找不到指定文件）.");
            return;
        }

        if (StrUtil.equalsIgnoreCase(FileUtil.extName(destFile), "pdf") && "0".equals(getPara("download"))) {
            getResponse().setContentType("application/pdf");
        } else {
            getResponse().setContentType("application/octet-stream");
        }

        getResponse().setHeader("Content-Disposition", "inline; filename=" + fileName);
        OutputStream rspOs = null;
        InputStream fileIs = FileUtil.getInputStream(destFile);
        try {
            rspOs = getResponse().getOutputStream();
            IoUtil.copy(fileIs, rspOs);
        } catch (Exception ignored) {
        } finally {
            IoUtil.close(rspOs);
            IoUtil.close(fileIs);
        }

        renderNull();
    }
}
